package com.jltx.javapoet;

import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.lang.model.element.Modifier;

/**
 * @author aidenquan
 * Created by junlintianxia on 2020/08/25.
 */
class JavaPoetDemo {
    public static void main(String[] args) {
        new JavaPoetDemo().createClass();
    }
    public void createClass() {
        try {
            //传入报名和TypeSpec生成最后的java类的描述对象
            JavaFile javaFile = JavaFile.builder("com.jltx.javapoet",createJavaPoetHelloClass()).build();
            String path = this.getClass().getResource("/").getPath();
            File file = new File(path).getParentFile();
            //生成类文件
            javaFile.writeTo(file);
            //java类内容以字符串的方式输出到控制台
            javaFile.writeTo(System.out);
            System.out.println("createJavaPoetHelloClass Success");
        } catch (Exception e) {
            System.out.println("createJavaPoetHelloClass Fail");
        }
    }
    public TypeSpec createJavaPoetHelloClass() {
        TypeSpec.Builder typeBuilder = TypeSpec.classBuilder("JavaPoetHello");    //创建类：
        typeBuilder.addModifiers(Modifier.FINAL, Modifier.PUBLIC);
        MethodSpec.Builder constructorMethodBuilder = MethodSpec.constructorBuilder();     //创建构造方法
        ClassName bundle = ClassName.get("android.os", "Bundle");
        //Bundle bundle = new Bundle();
        constructorMethodBuilder.addStatement("$T bundle = new $T()",bundle);
        constructorMethodBuilder.addStatement("data.$N()","toString");    //data.toString();
        // 添加printHelloWorld(String str)方法
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("printHelloWorld");
        methodBuilder.addModifiers(Modifier.PUBLIC);  //添加修饰符
        methodBuilder.addParameter(String.class, "str");   //添加方法入参数
        methodBuilder.returns(TypeName.get(Void.TYPE)); //添加方法返回值
        methodBuilder.addAnnotation(Override.class);  //方法里面添加注解
        methodBuilder.addStatement("System.out.println(str)");
        typeBuilder.addMethod(constructorMethodBuilder.build());
        typeBuilder.addMethod(methodBuilder.build());
        return typeBuilder.build();
    }

    public void testClass() {
        String clazzName = "com.jltx.javapoet.JavaPoetHello";
        try {
            Class helloCls = Class.forName(clazzName);
            Method helloM = helloCls.getDeclaredMethod("printHelloWorld",String.class);
            helloM.invoke(helloCls, "自动生成的类输出信息");
        } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
